<!--
/**
* Author: linchun
* Date: 2022-08-02 11:30
* Desc: sureOrder 确认订单
*/
-->
<template>
  <yy-page custom-class="page">
    <!-- #ifdef MP-WEIXIN || MP-ALIPAY -->
    <yy-navbar :border="false" :title="'确认订单'" left-icon-color="#fff" title-color="#fff" @left-click="backClick" :auto-back="false"></yy-navbar>
    <!-- #endif-->

    <view class="sure-order-page">
      <view class="sure-order-content mb20 pageBgColor">
        <!-- 影片影院信息 -->
        <film-info class="movie-info" :info="orderInfo" @timeComplete="handleTimeComplete"></film-info>
        <!-- 手机号 -->
        <mobile-input class="mobile-input" v-model="mobile" />
        <!-- 标题 -->
        <zm-title class="title-block fw500" :title="'请选择优惠方式'"></zm-title>

        <!-- 优惠券 -->
        <view class="coupon-main">
          <yy-cell class="custom-zm-cell" :is-link="true" ext-class="coupon-cell" :url="couponUrl">
            <view slot="title" class="title fw500">我的优惠券 </view>
            <view slot="label">
              <view class="label flex-s-m">
                您有
                <text class="fc-yellow padlr5">
                  {{ couponCount.filmCoupon || 0 }}
                </text>
                张可用券，已选
                <text class="fc-yellow padlr5">
                  {{ coupons.length }}
                </text>
                张
                <text v-if="leftCoupons && !hasCouponType2"
                  >，还需 <text class="fc-yellow padlr5"> {{ leftCoupons }} </text>张
                </text>
              </view>
            </view>
          </yy-cell>

          <view v-if="coupons.length > 0" class="usecoupon">
            <view class="text ell" v-for="(item, index) in coupons" :key="index">{{ `${item.couponName} , ${item.sD}~${item.eD}` }}</view>
          </view>

          <view v-if="coupons.length > 0" class="h20"></view>
        </view>
        <!-- 精选套券  clickCouponCheck内部选套票数据改变-->
        <coupon-info
          v-if="preDiscountPackageList.length > 0"
          class="coupon-info"
          :list="preDiscountPackageList"
          :is-checked="checkActive === 'discountPackage'"
          :check-package-id="checkPackageId"
          :choose-counpon-num="chooseCounponNum"
          :ticket-num="orderInfo.ticketNum"
          :able-package-coupon-len="ablePackageCouponLen"
          :show-more="discountPackageListLen > 3"
          :discount-price="getSingleSalePrice()"
          :content-rest="resetCoupons"
          :has-commerce-price="orderInfo.hasCommercePrice"
          @clickCouponCheck="clickCouponCheck"
          @toMoreTap="showPanel = true"
        />
        <!-- 特惠价 -->
        <view class="coupon-main" v-if="discountRule.totalPrice">
          <yy-cell class="custom-zm-cell" ext-class="tehui-cell" @myTap="chooseWay('discountRule', checkActive)">
            <view slot="title" class="title fw500">特惠价 </view>
            <view slot="label" class="label">
              <text> {{ `一键购买会员优惠券${orderInfo.hasCommercePrice ? ',' : ''}` }}</text>
              <text class="fc-yellow" v-if="orderInfo.hasCommercePrice"> 立省{{ discountRule.benefitPrice }}元 </text>
            </view>
            <view slot="value" class="value flex-s-m">
              <price custom-class="txt" :price="discountRule.totalPrice" unit-size="24" price-size="36" color="#FFB415"></price>
              <u-icon img-mode="aspectFit" :name="getImag(checkActive === 'discountRule')" size="34rpx"></u-icon>
            </view>
          </yy-cell>
          <view v-if="$auth.memberSystemStatus() === '1' && discountCoupon.discountCard && discountCoupon.discountCard.length > 0" class="card" @click="useCard">
            <view class="icon"></view>
            <view class="fs24 fc3 flex-1">特惠价可使用会员卡进行支付</view>
            <view class="fs24 fc3">{{ card ? '-￥' + cardMoney() : '选择' }}</view>
          </view>
        </view>
        <!-- 电商价 -->
        <yy-cell v-if="orderInfo.hasCommercePrice" class="custom-zm-cell" ext-class="dianshang-cell" :is-link="false" :arrow="false" @myTap="chooseWay('', checkActive)">
          <view slot="title" class="title fw500">电商价 </view>
          <view slot="label" class="label flex-s-m">
            <text> 不使用任何优惠 </text>
            <text v-if="abandonBenefitPrice">，将放弃{{ abandonBenefitPrice }}元的优惠 </text>
          </view>
          <view slot="value" class="value flex-s-m">
            <price custom-class="txt" :price="filmPrice" unit-size="24" price-size="36" color="#FFB415"></price>
            <u-icon :name="getImag(checkActive === '')" img-mode="aspectFit" size="34rpx"></u-icon>
          </view>
        </yy-cell>
        <!-- 购买须知 -->
        <buy-notice class="buy-notice" :content="orderInfo.refundExplain" v-if="orderInfo.refundExplain && orderInfo.refundExplain.length > 0"></buy-notice>
        <!-- 分割线 -->
        <u-line></u-line>
        <!-- 协议说明 -->
        <no-refund-agreement ref="agree" class="coupon-statement mb25"></no-refund-agreement>
      </view>
    </view>
    <order-info-footer
      v-model="showMore"
      :service-price="servicePrice()"
      :ext-pay-class="extPayClass"
      :list="getList()"
      :get-need-price="getNeedPrice"
      @showMore="showMore = !showMore"
      @goPay="goPay"
    ></order-info-footer>
    <!-- 更多套票popup -->
    <more-coupon-popup
      class="more-coupon-popup"
      v-model="showPanel"
      :info="moreCouponPopupInfo"
      :has-commerce-price="orderInfo.hasCommercePrice"
      @clickCouponCheck="clickCouponCheck"
      @chooseItem="handleChooseItem"
    />
    <discount-tip
      v-if="showDiscount"
      v-model="showDiscount"
      :discount-package-list="preDiscountPackageList"
      :discount-rule="discountRule"
      :ticket-num="orderInfo.ticketNum"
      :discount-price="getSingleSalePrice()"
      :able-package-coupon-len="ablePackageCouponLen"
      @use="goPay(true)"
      @useDiscountRule="chooseWay('discountRule', checkActive)"
      @useCoupon="clickCouponCheck"
    />
  </yy-page>
</template>
<script>
  import ZmTitle from '@/pagesOrder/commons/ZmTitle/index.vue'
  import MobileInput from '@/pagesOrder/components/MobileInput/index.vue'
  import NoRefundAgreement from '@/pagesOrder/components/NoRefundAgreement/index.vue'
  import Price from '@/components/Price'
  import mixinIndex from './mixin/index'
  import orderMixin from './mixin/orderMixin'
  import FilmInfo from './components/FilmInfo'
  import CouponInfo from './components/CouponInfo'
  import MoreCouponPopup from './components/MoreCouponPopup'
  import DiscountTip from './components/DiscountTip'
  import BuyNotice from './components/BuyNotice'

  import { locSelCoupon, locPreOrderInfo, locSelCard } from '@/utils/locStore/data'
  import OrderInfoFooter from '@/components/OrderInfoFooter'

  export default {
    mixins: [mixinIndex, orderMixin],
    components: {
      ZmTitle,
      FilmInfo,
      CouponInfo,
      // ViewerInfo,
      MoreCouponPopup,
      DiscountTip,
      NoRefundAgreement,
      Price,
      BuyNotice,
      MobileInput,
      OrderInfoFooter
    },
    data() {
      return {
        orderId: '',
        mobile: '', //手机号
        showMore: false,
        showPanel: false,
        showDiscount: false,
        query: {},
        orderInfo: {},
        discountCoupon: {
          discountRule: {},
          discountPackage: []
        },
        checkPackageId: '', // 选择购买优惠套票id
        checkDiscountRule: '', // 选择特惠价id
        couponCount: {}, // 可用优惠券数量
        coupons: [], // 选中的券信息
        card: null, // 选中的卡信息
        checkActive: '', //定位类型 默认'' 电商价
        chooseCounponNum: 0, //选中套票的数量
        checkPackageItem: {}, //选中套票的对象
        resetCoupons: false, //重置套票
        realnameDataList: [], // 选择观影人信息数据
        preDiscountPackageList: [],
        isTimeOut: false // 是否倒计时结束
      }
    },
    // #ifdef H5
    beforeRouteLeave(to, from, next) {
      const toPath = to.path
      const toPathArr = ['/pages/mine/index', '/pagesOrder/chooseSet/index', '/pagesOrder/order/filmList']
      if (toPathArr.includes(toPath) && !this.isTimeOut) {
        //来源为选座
        this.$msg
          .showModal({
            title: '',
            content: '后退将会清空选座信息，是否确认后退？',
            cancelText: '取消',
            confirmText: '确认'
          })
          .then(() => {
            this.handleUnlockSeat()
              .then(() => {
                next()
              })
              .catch(() => {
                this.isTimeOut = true
                next(false)
              })
          })
          .catch(() => {
            this.isTimeOut = false
            next(false)
            //不处理
          })
      } else {
        next()
      }
    },
    // #endif
    created() {
      //  #ifdef MP-ALIPAY || MP-TOUTIAO

      const fromPathArr = ['pages/mine/index', 'pagesOrder/chooseSet/index', 'pagesOrder/order/filmList']
      const fromPath = this.$tools.getCurrentPage().fromPath
      this.fromPath = fromPath

      if (fromPathArr.includes(fromPath) && !this.isTimeOut) {
        this.$tools.enable('后退将会清空选座信息，是否确认后退？')
      }
      // #endif
    },
    //  #ifdef MP-ALIPAY || MP-TOUTIAO
    onUnload() {
      this.$tools.disable()
      const fromPathArr = ['pages/mine/index', 'pagesOrder/chooseSet/index', 'pagesOrder/order/filmList']
      // const fromPath = this.$tools.getCurrentPage().fromPath

      //isToPay 字节跳转首页会触发onUnload，加上点击按钮后的判断处理
      if ((fromPathArr.includes(this.fromPath) && !this.isTimeOut, !this.isToPay)) {
        this.handleUnlockSeat(0, false)
      }
    },
    // #endif
    onLoad(options) {
      locSelCoupon.remove() //清空选券数据
      locSelCard.remove() //清空选券数据
      locPreOrderInfo.remove() //清空预支付数据
      this.$auth.removeNameList() //清空观影人信息选择
      // 接收url传参
      this.query = options || {}
      this.orderId = this.query.orderId || ''
      // 初始化常用数据
      this.init(options)
    },
    computed: {
      // 获取总座位数(购买票数)
      ticketNum() {
        const ticketNum = this.orderInfo.ticketNum || 0
        return this.$utils.isNaNStr(ticketNum)
      },
      couponUrl() {
        //优惠券跳转url
        const url = 'filmCoupon/index'
        const allUrl =
          '/pagesOrder/' +
          url +
          '?fromPage=sureOrder&maxNum=' +
          (this.getTicketNum() || 0) +
          '&singleSeatPrice=' +
          this.getSingleSalePrice() +
          '&filmPrice=' +
          this.filmPrice +
          '&orderId=' +
          this.orderId
        return allUrl
      },
      discountPackageList() {
        //套票列表
        return this.discountCoupon.discountPackage || []
      },
      discountPackageListLen() {
        //套票列表长度
        return (this.discountPackageList && this.discountPackageList.length) || 0
      },
      curCheckPackageItem() {
        return this.discountPackageList.find((i) => i.commodityId == this.checkPackageId) || {}
      },
      firstItem() {
        let item = {}
        if (this.checkActive === 'discountPackage') {
          if (this.unpaidOrderInfo.type && this.unpaidOrderInfo.type === 'discountPackage') {
            item = this.unpaidOrderInfo //存在待支付套票
          } else if (this.checkPackageItem.commodityId) {
            item = this.checkPackageItem //用户或默认选择套票
          } else if (this.preDiscountPackageList.length > 0) {
            item = this.preDiscountPackageList[0]
          }
        }
        return item
      },
      moreCouponPopupInfo() {
        //更多套票信息
        return {
          discountPackageList: this.discountPackageList || [],
          ablePackageCouponLen: this.ablePackageCouponLen || 0,
          checkActive: this.checkActive,
          checkPackageId: this.checkPackageId,
          chooseCounponNum: this.chooseCounponNum,
          ticketNum: this.orderInfo.ticketNum,
          singleSalePrice: this.getSingleSalePrice()
        }
      },
      discountRule() {
        //特惠价对象
        return this.discountCoupon.discountRule || {}
      },
      // 判断所选优惠券类型 1 兑换券 2优惠券(备注优惠券只能用一张)
      hasCouponType2() {
        //couponType 1 兑换券 2优惠券
        return !!this.coupons.filter((i) => i.couponType === '2').length
      },
      // 可用券包里面的券数量
      ablePackageCouponLen() {
        if (this.hasCouponType2) {
          return this.ticketNum
        }
        return this.ticketNum - this.coupons.length
      },
      // 还需优惠券
      leftCoupons() {
        const ticketNum = this.getTicketNum()
        const couponsLen = this.coupons.length
        if (ticketNum > couponsLen) {
          return ticketNum - couponsLen
        }
        return ''
      },
      // 选择兑换券时,计算补差金额
      calcMyCouponPrice() {
        const coupons = this.coupons.filter((item) => item.couponType === '1')
        const differenceTotal = this.$utils.arrayCalc(coupons, 'difference')
        return differenceTotal
      },
      // 计算所勾选套票需付费金额（含补差）
      calcPackagePrice() {
        // if (!this.checkPackageId) {//不是选套票不参与计算
        //   return 0
        // }
        const checkPackageItem = this.unpaidOrderInfo.type
          ? this.checkPackageItem //存在待支付订单
          : this.curCheckPackageItem
        let { chooseNum, saleTotalPrice, diffPrice } = checkPackageItem
        chooseNum = this.$utils.isNaNStr(chooseNum)
        saleTotalPrice = this.$utils.isNaNStr(saleTotalPrice)
        diffPrice = this.$utils.isNaNStr(diffPrice)
        const p = chooseNum * saleTotalPrice + diffPrice * this.ablePackageCouponLen
        return p
      },
      // 所购影票(包含单张价格*票数)原价也即电商价
      filmPrice() {
        return this.$utils.isNaNStr(this.orderInfo.salePrice)
      },
      // 获取折扣后的价格
      getNeedPrice() {
        if (this.checkActive === 'discountPackage') {
          //套票
          const p = this.calcMyCouponPrice + Number(this.calcPackagePrice)
          return this.$utils.toFixed(p)
        } else if (
          //特惠价
          this.checkActive === 'discountRule'
        ) {
          const p = Number(this.discountRule.totalPrice) + Number(this.discountRule.technicalServiceFee) * this.ticketNum
          if (this.card) {
            return 0
          }
          return this.$utils.toFixed(p)
        }
        const couponMoney = this.caclFilmCoupon() //兑换券完全支付或优惠券支付
        const prePrice = this.getPrePrice() //无其他商品此处即原价或电商价
        const needPay = prePrice - couponMoney
        return this.$utils.toFixed(needPay)
      },
      // 电商价显示放弃优惠价
      abandonBenefitPrice() {
        let money = ''
        if (this.discountPackageListLen > 0) {
          //存在套票优惠
          money = this.discountPackageList[0].discountPrice //后端确认按discountPrice这个从大到小排序
        } else if (this.discountPackageListLen === 0 && this.discountRule.benefitPrice) {
          //不存在套票 存在特惠价
          money = this.discountRule.benefitPrice
        }
        return money
      },
      hasNoDiscountRulePrice() {
        //特惠价类型 无数据情况不可点击支付
        return this.checkActive === 'discountRule' && !(this.$utils.isNaNStr(this.discountRule.totalPrice) > 0)
      },
      extPayClass() {
        //#ifdef MP-TOUTIAO
        if (this.coupons.length > 0) {
          if (this.coupons[0].couponType === '2') {
            if (+this.coupons.reduce < +this.orderInfo.singleSalePrice) {
              return 'disabledPay'
            }
          } else if (this.coupons[0].couponType === '1') {
            if (this.coupons.length < +this.orderInfo.ticketNum) {
              return 'disabledPay'
            }
          }
        } else {
          return 'disabledPay'
        }
        //#endif
        return this.hasNoDiscountRulePrice || this.isTimeOut || this.checkActive === 'no-use' ? 'disabledPay' : ''
      },
      unpaidOrderInfo() {
        let unpaidOrder = {}
        // 存在待支付套票订单--定位套票
        if (this.orderInfo.packageDiscountData && this.orderInfo.packageDiscountData.commodityId) {
          unpaidOrder = this.orderInfo.packageDiscountData
          unpaidOrder.type = 'discountPackage'
          unpaidOrder.chooseNum = this.chooseCounponNum
        } else if (
          //定位特惠价 并赋值id
          this.orderInfo.discountRule &&
          this.orderInfo.discountRule.ruleId
        ) {
          unpaidOrder = this.orderInfo.discountRule
          unpaidOrder.type = 'discountRule'
        }
        return unpaidOrder
      },
      getCheckActive() {
        let checkActive = ''
        if (this.query.discountType === 'discountPackage' && this.discountPackageListLen > 0) {
          //套票进来有套票数据
          //定位套票
          checkActive = 'discountPackage'
        } else if (this.query.discountType === 'discountRule' && this.$utils.isNaNStr(this.discountRule.totalPrice) > 0) {
          //特惠价进来 有特惠价
          //定位特惠价
          checkActive = 'discountRule'
        } else if (
          //套票或特惠价进来缓存问题定位
          (this.query.discountType === 'discountPackage' && this.discountPackageListLen === 0) ||
          (this.query.discountType === 'discountRule' && this.$utils.isNaNStr(this.discountRule.totalPrice) == 0)
        ) {
          checkActive = 'no-use'
        } else if (
          //去支付进来
          !this.query.discountType &&
          this.unpaidOrderInfo.type
        ) {
          checkActive = this.unpaidOrderInfo.type
        }
        return checkActive
      }
    },
    onShow() {
      this.isToPay = false
      this.onShowInit().then(async () => {
        // 清相关缓存
        this.removeStorageData()
      })
    },
    methods: {
      init(options) {
        this.getOrderInfo().then(() => {
          // 定位类型
          if (options.discountType) {
            this.checkActive = options.discountType
          } else {
            // 存在套票数据 优惠支付方式选择
            this.checkActive = this.getCheckActive
          }
          this.getFilmDiscountByOrderId()
        })
        this.getAcceptData()
      },
      onShowInit() {
        const fromRealName = uni.getStorageSync('fromRealName') //储存来源是否为观影人选择列表页 值为'1'代表从观影人列表跳回
        const payIndex = uni.getStorageSync('payIndex') //储存来源是否为支付页面 值为'1'代表支付页面跳回
        const filmCouponBack = uni.getStorageSync('filmCouponBack') //储存来源是否为优惠券自定义返回券 值为'1'代表优惠券页面跳回
        this.card = locSelCard.get() || null
        console.log('card', this.card)
        if (this.card) {
          this.chooseWay('discountRule', this.checkActive)
        }
        if (fromRealName || payIndex || filmCouponBack) {
          // 观影人信息回跳 只刷新观影人信息列表
          if (fromRealName) {
            this.realnameDataList = this.$auth.getRealNameList() || [] //观影人信息
          }
          return Promise.resolve()
        } else {
          const fromCouponList = uni.getStorageSync('fromCouponList') //储存来源是否为优惠券选择列表页 值为'1'代表从优惠券列表选择确定跳回
          if (fromCouponList) {
            this.clearCard() // 用完券取消使用卡
            this.handelCoupon() // 优惠券选择处理
          }

          //券页面回来刷新数量（添加券）
          return uni.$api.orderFilm.getUsableCount({ orderId: this.orderId }).then((res) => {
            this.couponCount = res || {}
            return res
          })
        }
      },
      getImag(checked) {
        const fileName = checked ? 'icon-selected' : 'icon-unselected'
        return this.$utils.getOssImg(fileName) || ''
      },
      async getAcceptData() {
        this.agreeChecked = await uni.$api.user.getAcceptData()
      },
      //获取订单详情
      getOrderInfo() {
        const d = {
          orderId: this.orderId
        }
        return uni.$api.orderFilm.getOrderInfo(d).then((data) => {
          this.orderInfo = data || {}
          if (!this.orderInfo.cinemaName) {
            this.orderInfo.cinemaName = data.cinemaInfo.cinemaName
          }
          this.mobile = this.orderInfo.lockMobile || ''
          return data
        })
      },
      //排序
      compare(property) {
        return function (a, b) {
          var value1 = a[property]
          var value2 = b[property]
          /*
           * value2 - value1; ——> 降序
           * value1 - value2; ——> 升序
           */
          return value1 - value2 //升序排序
        }
      },
      changePackageList(isFirst = false) {
        //排序
        let payMoney = 0
        let first = null
        let firstNum = 1
        const lastNum = isFirst ? this.orderInfo.ticketNum : this.orderInfo.ticketNum - this.coupons.length
        this.discountCoupon.discountPackage.forEach((item) => {
          let num = parseInt(lastNum / item.couponNum)

          if (lastNum % item.couponNum !== 0) {
            num++
          }
          if (first) {
            if (item.payPrice * num < payMoney) {
              first = item
              firstNum = num
              payMoney = item.payPrice * num
            } else if (item.payPrice * num === payMoney) {
              if (first.couponNum * firstNum < item.couponNum * num) {
                first = item
                firstNum = num
                payMoney = item.payPrice * num
              }
            }
          } else {
            first = item
            firstNum = num
            payMoney = item.payPrice * num
          }
        })
        console.log('first', first)
        if (first) {
          this.discountCoupon.discountPackage = this.discountCoupon.discountPackage.filter((item) => {
            return item.commodityId !== first.commodityId
          })
        }

        this.discountCoupon.discountPackage.sort(this.compare('saleTotalPrice'))
        if (first) {
          this.discountCoupon.discountPackage.unshift(first)
        }
        this.preDiscountPackageList = this.$utils.deep(this.discountPackageList)
      },
      // 获取影票优惠政策
      getFilmDiscountByOrderId() {
        const data = { orderId: this.orderId }
        uni.$api.discountRule.getFilmDiscountByOrderId(data).then((res) => {
          this.discountCoupon = res //修复只有特惠价 定位问题 系异步执行 导致discountRule取值
          if (res.couponList && res.couponList.length > 0) {
            res.couponList.map((item) => {
              item.isSel = '1'
              item.type = '1'
            })
            locSelCoupon.set(res.couponList)
            this.handelCoupon(true)
          }

          if (res.discountPackage.length > 0) {
            //有套票数据
            let maxNum = 0
            res.discountPackage.forEach((i) => {
              const couponNum = this.$utils.isNaNStr(i.couponNum)
              let min = 0
              if (this.coupons.length === +this.orderInfo.ticketNum && this.checkActive === 'discountPackage') {
                min = 0
              } else {
                min = Math.ceil(this.ablePackageCouponLen / couponNum) || 1
                console.log('ablePackageCouponLen', min)
              }
              if (min > 0 && min > i.maxNum) {
                min = i.maxNum
              }
              i.chooseNum = min // 默认选择套票数量
              i.minNum = min // 最小套票选择数量
              if (i.commodityId == this.unpaidOrderInfo.commodityId) {
                maxNum = this.$utils.isNaNStr(i.maxNum)
              }
            })

            //处理最优票价(鸿伟+花花要求)
            this.changePackageList()
            console.log('this.checkActive', this.checkActive, this.checkPackageItem)
            if (this.checkActive === 'discountPackage') {
              //套票
              if (this.unpaidOrderInfo.type) {
                //存在待支付
                this.checkPackageItem = this.unpaidOrderInfo
                const couponNum = this.$utils.isNaNStr(this.unpaidOrderInfo.couponNum)
                this.checkPackageId = this.unpaidOrderInfo.commodityId
                const min = Math.ceil(this.ablePackageCouponLen / couponNum) || 1
                this.checkPackageItem.chooseNum = min
                this.chooseCounponNum = min
                if (maxNum && maxNum < min) {
                  this.checkPackageItem.chooseNum = maxNum
                  this.chooseCounponNum = maxNum
                }
              } else {
                //选择进入
                if (this.coupons.length !== +this.orderInfo.ticketNum) {
                  const [firstItem = {}] = this.discountCoupon.discountPackage || []
                  this.checkPackageId = firstItem.commodityId || ''
                  this.chooseCounponNum = firstItem.minNum
                  this.checkPackageItem = firstItem
                }
              }
            }
          }
          // 有特惠价赋值
          this.checkDiscountRule = this.unpaidOrderInfo.ruleId || this.discountRule.ruleId || ''
          //如果无指定定位则优先定位优惠套票
          if (!this.unpaidOrderInfo.type && this.discountPackageListLen > 0) {
            //有套票数据
            const [firstItem = {}] = this.discountCoupon.discountPackage || []
            this.checkPackageId = firstItem.commodityId || ''
            this.chooseCounponNum = firstItem.minNum
          }
        })
      },
      // 处理选中后的优惠券
      handelCoupon() {
        // 优惠券选择情况
        const checkCoupon = locSelCoupon.get() || []
        // coupons赋值
        if (checkCoupon.length > 0) {
          this.coupons = checkCoupon || []
          if (this.hasCouponType2) {
            //优惠券支付
            this.checkActive = 'allCoupons' //不需要定位
            this.clearCheckedCoupons()
          } else {
            //选择兑换券
            if (
              //兑换券+套票支付
              this.coupons.length < +this.orderInfo.ticketNum
            ) {
              if (this.discountPackageListLen > 0) {
                //存在套票
                // 选择兑换券 & 兑换券有数量 &  可用券包券数量 > 0  & 没有选择套票 时 默认选择第一种套票
                this.checkActive = 'discountPackage'
                if (this.coupons.length > 0) {
                  const checkPackageItem = this.discountPackageList.find((i) => i.commodityId == this.checkPackageId) || {}

                  this.clearCheckedCoupons()
                  this.checkPackageId = checkPackageItem.commodityId
                  this.checkPackageItem = checkPackageItem
                  this.chooseCounponNum = checkPackageItem.minNum
                } else {
                  this.clearCheckedCoupons()
                  const [firstItem = {}] = this.preDiscountPackageList || []
                  this.checkPackageId = firstItem.commodityId
                  this.checkPackageItem = firstItem
                  this.chooseCounponNum = firstItem.minNum
                }
                this.resetDiscountPackage(true, 'couponList')
                // firstItem.chooseNum > firstItem.minNum
                //   ? firstItem.chooseNum
                //   : firstItem.minNum
              } else {
                //不存在套票 不让支付
                this.checkActive = 'no-use'
              }
            } else if (this.coupons.length === +this.orderInfo.ticketNum) {
              //完全兑换券支付
              this.checkActive = 'allCoupons'
              this.clearCheckedCoupons()
            }
          }
          // 1.重新获取优惠券选择情况2.重置套票min
          this.resetDiscountPackage(true)
        } else {
          this.coupons = []
          const fromCouponList = uni.getStorageSync('fromCouponList') //储存来源是否为优惠券选择列表页 值为'1'代表从优惠券列表选择确定跳回
          if (fromCouponList) {
            //非第一次
            // 不可支付
            if (this.discountPackageListLen > 0) {
              this.checkActive = 'discountPackage'
            } else {
              this.checkActive = 'no-use'
            }
            locSelCoupon.remove()
            //非套票优惠方式清空优惠券选择数据
            this.clearCheckedCoupons()
          }
          this.resetDiscountPackage(true, 'couponList')
        }
        uni.removeStorageSync('fromCouponList') //清空状态 完成闭合
      },
      chooseWay(type, originType) {
        console.log('chooseWay', type, originType)
        // todo 1有选券清券2之前是套票清套票id3重置套票列表
        if (type === originType) {
          return
        }
        //设置选择方式
        this.checkActive = type
        if (type !== 'discountRule') {
          this.clearCard()
        }
        if (type !== 'discountPackage') {
          let freshCoupon = false
          if (this.coupons.length > 0) {
            this.clearCoupons()
          }
          //所选非套票
          if (originType === 'discountPackage' || originType === 'allCoupons') {
            //原来选择套票 重置套票
            freshCoupon = true
            this.clearCheckedCoupons()
            this.resetDiscountPackage(freshCoupon)
          }
        }
        if (type === '') {
          this.changePackageList(true)
        }
      },
      clickCouponCheck(item, curChooseNum) {
        if (this.hasCouponType2) {
          //存在优惠券 清除缓存
          this.clearCoupons()
        }
        if (this.card) {
          this.clearCard()
        }
        this.checkActive = 'discountPackage'
        this.clearCheckedCoupons() //先清后赋值可更新
        this.checkPackageItem = item
        if (item && item.commodityId) {
          this.checkPackageId = ''
        }
        if (curChooseNum == 0) {
          //套票数量为0时allCoupons,因为只有券满足后才可减少到0
          this.checkActive = 'allCoupons'
        }
        this.checkPackageId = item.commodityId
        this.chooseCounponNum = curChooseNum
        this.checkPackageItem.chooseNum = curChooseNum
        this.resetDiscountPackage(true)
      },
      handleChooseItem(item, curChooseNum) {
        if (item.commodityId) {
          // 有选择项情况下先剔除选中原来所在位置
          const index = this.preDiscountPackageList.findIndex((i) => i.commodityId == item.commodityId)
          if (index !== -1) {
            //找出索引赋值
            this.preDiscountPackageList.splice(index, 1)
            this.checkPackageId = item.commodityId
          }
          this.preDiscountPackageList.unshift(item) //头部添加
          this.checkPackageItem.chooseNum = curChooseNum
          this.resetDiscountPackage(true)
        }
      },
      validMobile() {
        let str = ''
        if (!this.mobile) {
          str = '手机号不能为空'
        } else if (!this.$auth.validateTel(this.mobile)) {
          str = '手机号格式有误'
        }
        return str
      },
      // 生成预下单信息
      createPreInfo() {
        let preInfo = {
          orderId: this.orderId,
          // 影片消息
          film: {
            filmPrice: this.filmPrice, // 影片总价
            coupons: this.checkActive === 'discountPackage' || this.checkActive === 'allCoupons' ? this.coupons : [], // 影票信息
            discount: this.checkActive === 'discountPackage' ? this.filmDiscount : null, // 影片用券后的价格
            otherPayInfo: this.orderInfo.otherPayInfo || []
          },
          needPay: this.getNeedPrice,
          lockMobile: this.mobile
        }
        preInfo = this.$utils.deep(preInfo)
        return preInfo
      },
      purchaseLimit(chooseNum) {
        //只考虑不用券的情况
        const packageCouponLen = this.$utils.isNaNStr(this.checkPackageItem.couponNum) * this.$utils.isNaNStr(chooseNum) + this.coupons.length

        return this.checkActive === 'discountPackage' && packageCouponLen < this.getTicketNum()
      },
      async goPay(surePay) {
        if (this.checkActive === '' && !surePay && (this.discountRule.totalPrice || this.preDiscountPackageList.length > 0)) {
          //未选择优惠且存在优惠时弹出提示
          this.showDiscount = true
          return
        }
        if (this.checkActive === 'no-use' || this.isTimeOut || this.hasNoDiscountRulePrice) {
          //无数据缓存造成||超时等原因造成不可支付||特惠价类型 无数据情况不可点击支付
          return
        }
        if (!this.$refs.agree) {
          return
        }
        if (!this.$refs.agree.feChecked) {
          //勾选接受协议
          return this.$refs.agree.openPopup()
        }
        const mobileMsg = this.validMobile()
        if (mobileMsg) {
          //验证手机号输入
          this.$msg.toast(mobileMsg)
          return
        }
        // 如果选择了套票先判断是否可用
        if (this.checkPackageId && this.checkActive === 'discountPackage') {
          const checkPackageItem = this.unpaidOrderInfo.type
            ? this.checkPackageItem //存在待支付订单
            : this.curCheckPackageItem

          this.chooseCounponNum = checkPackageItem.chooseNum
          if (this.purchaseLimit(this.chooseCounponNum)) {
            this.$msg.toast('用券数必须和座位数一致')
            return
          }
          uni.$api.mall
            .checkCommodityStock({
              mallCommodityId: this.checkPackageId,
              discountCommodityNum: this.$utils.isNaNStr(this.chooseCounponNum)
            })
            .then((res) => {
              console.log('======res', res)
              if (res && res[0]) {
                const stockNum = res[0].stockNum || 0
                if (this.purchaseLimit(stockNum)) {
                  this.$msg.toast('所选券包限购' + stockNum + '份，请选择其他券包购买')
                  return
                }
                this.handleGoPay(this.chooseCounponNum)
              }
            })
            .catch((err) => {
              if (err.data.content) {
                this.$msg.toast(err.data.content)
              }
              return
            })
        } else {
          // #ifndef MP-WEIXIN
          this.handleGoPay(this.chooseCounponNum)
          // #endif
          // #ifdef MP-WEIXIN
          await this.getTemplateIds()
          wx.getSetting({
            withSubscriptions: true,
            success: (res) => {
              console.log(res, 'set-res')
              if (res.subscriptionsSetting) {
                const { mainSwitch = true } = res.subscriptionsSetting
                if (!mainSwitch) {
                  this.handleGoPay(this.chooseCounponNum)
                } else {
                  this.handleSubscribe(this.tmplIds)
                }
              }
            },
            fail: (err) => {
              this.handleGoPay(this.chooseCounponNum)
              console.log(err, 'set-err')
            }
          })
          // #endif
        }
      },
      handleGoPay(chooseNum) {
        chooseNum = chooseNum || ''
        const preInfo = this.createPreInfo()
        const query = {
          lockMobile: this.mobile,
          filmOrderId: preInfo.orderId,
          orderType: 'film',
          needPay: preInfo.needPay,
          cinemaId: this.orderInfo.cinemaId,
          realNameIds: this.realnameDataList.map((i) => i.realNameId).join(','),
          discountRuleId: this.checkActive === 'discountRule' ? this.checkDiscountRule : '',
          cardId: this.checkActive === 'discountRule' && this.card ? this.card.id : '',
          discountCommodityId: this.checkActive === 'discountPackage' ? this.checkPackageId : '',
          discountCommodityNum: this.checkActive === 'discountPackage' ? chooseNum : ''
        }
        locPreOrderInfo.set(preInfo)
        this.isToPay = true
        this.$tools.navigateTo('/pagesOrder/pay/index', query)
      },
      removeStorageData() {
        uni.removeStorageSync('filmCouponBack') //清空状态 完成闭合
        uni.removeStorageSync('payIndex') //清空状态 完成闭合
        uni.removeStorageSync('fromRealName') //清空状态 完成闭合
      },
      // 重置券包数量
      resetDiscountPackage(refresh = false, fromPath = '') {
        console.log('resetDiscountPackage', refresh, fromPath)
        // 重置最小数量
        this.discountPackageList.forEach((i) => {
          const couponNum = this.$utils.isNaNStr(i.couponNum)
          let min = 0
          if (this.coupons.length === +this.orderInfo.ticketNum && this.checkActive === 'discountPackage') {
            min = 0
          } else {
            min = Math.ceil(this.ablePackageCouponLen / couponNum) || 1
            //套票中的券除还需支付的座位数取整，获取还需使用的套票数量
          }
          if (min > 0 && min > i.maxNum) {
            min = i.maxNum
          }
          i.chooseNum = i.commodityId == this.checkPackageId && this.chooseCounponNum ? this.chooseCounponNum : min
          if (fromPath && i.commodityId == this.checkPackageId) {
            i.chooseNum = min
            this.chooseCounponNum = min
          }
          i.minNum = min
          // if (i.commodityId == this.checkPackageId) {
          //   if (this.firstItem.chooseNum > min) {
          //     i.chooseNum = this.firstItem.chooseNum // 同步用户选择套票数量
          //   } else {
          //     i.chooseNum = min // 同步用户选择套票数量
          //   }
          // }
        })
        this.preDiscountPackageList.forEach((i) => {
          const couponNum = this.$utils.isNaNStr(i.couponNum)
          let min = 0
          if (this.coupons.length === +this.orderInfo.ticketNum && this.checkActive === 'discountPackage') {
            min = 0
          } else {
            min = Math.ceil(this.ablePackageCouponLen / couponNum) || 1
          }
          if (min > 0 && min > i.maxNum) {
            min = i.maxNum
          }
          i.chooseNum = i.commodityId == this.checkPackageId && this.chooseCounponNum ? this.chooseCounponNum : min
          if (fromPath && i.commodityId == this.checkPackageId) {
            i.chooseNum = min
            this.chooseCounponNum = min
          }
          i.minNum = min
          // if (i.commodityId == this.checkPackageId) {
          //   if (this.firstItem.chooseNum > min) {
          //     i.chooseNum = this.firstItem.chooseNum // 同步用户选择套票数量
          //   } else {
          //     i.chooseNum = min // 同步用户选择套票数量
          //   }
          // }
        })
        if (fromPath === 'couponList') {
          this.changePackageList()
          if (this.coupons.length !== +this.orderInfo.ticketNum) {
            const [firstItem = {}] = this.discountCoupon.discountPackage || []
            this.checkPackageId = firstItem.commodityId || ''
            this.chooseCounponNum = firstItem.minNum
            this.checkPackageItem = firstItem
          }
        }

        // if (refresh) {
        //   this.refreshCouponInfoComp()
        // }
      },
      refreshCouponInfoComp() {
        this.resetCoupons = true
        setTimeout(() => {
          this.resetCoupons = false
        }, 0)
      },
      clearCoupons() {
        locSelCoupon.remove()
        this.coupons = []
      },
      clearCard() {
        locSelCard.remove()
        this.card = null
      },
      clearCheckedCoupons() {
        this.chooseCounponNum = 0
        this.checkPackageItem = {}
      },
      // 处理后退
      backClick() {
        const route = this.$tools.getCurrentPage()
        const fromPath = route.fromPath
        const fromPathArr = ['pages/mine/index', 'pagesOrder/chooseSet/index', 'pagesOrder/order/filmList']
        if (fromPathArr.includes(fromPath) && !this.isTimeOut) {
          //来源为选座
          this.$msg
            .showModal({
              title: '',
              content: '后退将会清空选座信息，是否确认后退？',
              cancelText: '取消',
              confirmText: '确认'
            })
            .then(() => {
              this.handleUnlockSeat()
            })
            .catch(() => {
              this.isTimeOut = false
              //不处理
            })
        } else {
          //比如来源为我的订单
          let pre = -1
          if (route.cuttentRoute === 'pagesOrder/filmCoupon/index' || route.cuttentRoute === 'pages/pay/index' || route.cuttentRoute === 'pagesOrder/chooseViewers/index') {
            //当前页面为优惠券列表
            pre = -2
          }
          this.handleUnlockSeat(pre)
        }
      },
      handleTimeComplete() {
        this.isTimeOut = true
        let pre = -1
        //#ifdef MP-WEIXIN || MP-ALIPAY || MP-TOUTIAO
        if (
          this.$tools.getCurrentPage().cuttentRoute === 'pagesOrder/filmCoupon/index' ||
          this.$tools.getCurrentPage().cuttentRoute === 'pages/pay/index' ||
          this.$tools.getCurrentPage().cuttentRoute === 'pagesOrder/chooseViewers/index'
        ) {
          //当前页面为优惠券列表
          pre = -2
        }
        this.handleUnlockSeat(pre)
        //#endif
        //#ifdef H5
        const curPagePath = window.location.href
        if (curPagePath.indexOf('pagesOrder/filmCoupon/index') > -1 || curPagePath.indexOf('pages/pay/index') > -1 || curPagePath.indexOf('pagesOrder/chooseViewers/index') > -1) {
          //当前页面为优惠券列表
          pre = -2
        }
        this.handleUnlockSeat(pre, false)
        //#endif
      },
      handleUnlockSeat(pre = -1, clickBack = true) {
        // 解锁位置操作
        const d = { orderId: this.query.orderId }
        this.$msg.loading()
        return uni.$api.orderFilm
          .unLockSeat(d)
          .then((res) => {
            this.$msg.hideLoading()
            this.isTimeOut = true
            //#ifdef MP-WEIXIN || MP-ALIPAY || MP-TOUTIAO
            if (clickBack) {
              this.$tools.navigateTo(pre)
            } else {
              //支付宝传 clickBack=false触发上个页面的onShow刷新
              const pages = getCurrentPages()
              const page = pages[pages.length - 1]
              if (page) {
                page.onShow()
              }
            }

            //#endif
            //#ifdef H5
            if (clickBack) {
              return Promise.resolve(res)
            } else {
              this.$tools.navigateTo(pre)
            }
            //#endif
          })
          .catch((err) => {
            // 接口报错第2次能后退
            this.isTimeOut = true
            //#ifdef H5
            return Promise.reject(err)
            //#endif
          })
      },

      useCoupon() {
        const query = {
          fromPage: 'sureOrder',
          maxNum: this.getTicketNum() || 0,
          singleSeatPrice: this.getSingleSalePrice(),
          filmPrice: this.filmPrice,
          orderId: this.orderId
        }
        const url = 'filmCoupon/index'
        this.$tools.navigateTo(`/pagesOrder/${url}`, query)
      },
      useCard() {
        this.$tools.navigateTo('/pagesOrder/card/index', {
          fromPage: 'sureOrder',
          orderId: this.orderId,
          filmPrice: this.filmPrice,
          totalPrice: this.discountRule.totalPrice
        })
      },
      getList() {
        return this.listData()
      },
      handleSubscribe(tmplIds) {
        console.log('this.tmplIds', this.tmplIds)
        // 发起订阅
        wx.requestSubscribeMessage({
          tmplIds,
          success: (res) => {
            console.log(res, 'sub-res')
            this.handleGoPay(this.chooseCounponNum)
          },
          fail: (err) => {
            console.log(err, 'sub-err')
            this.handleGoPay(this.chooseCounponNum)
            // const turnArr = [20001, 20003, 20004]
            // if (turnArr.includes(+err.errCode)) {
            // } else {
            //   this.$msg.toast('网络出现问题，请重试')
            // }
          }
        })
      },
      async getTemplateIds() {
        const res = await uni.$api.public.getTemplateList({ templateType: '2' })
        this.tmplIds = res.map((item) => item)
        console.log(res)
      }
    }
  }
</script>
<style lang="scss">
  /* #ifdef MP-ALIPAY */
  /deep/.coupon-cell {
    margin-bottom: 0rpx !important;
  }
  /deep/.tehui-cell {
    margin-top: 25rpx !important;
  }
  /deep/.dianshang-cell {
    margin-top: 20rpx !important;
  }
  /deep/.txt {
    margin-right: 18rpx;
  }
  .title {
    font-size: 30rpx;
    font-weight: bold;
    margin-bottom: 18rpx;
    .more {
      height: 30rpx;
      line-height: 30rpx;
      font-size: 26rpx;
      font-weight: 400;
      color: #adb5b7;
    }
  }
  .label {
    font-size: 24rpx;
  }
  .value {
    .txt {
      margin-right: 18rpx;
    }
  }
  /* #endif*/
  .page {
    height: 100vh;
    overflow-y: hidden;
    background: #f3f5f7;
    box-sizing: border-box;
    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      height: 500rpx;
      background: linear-gradient(90deg, #4fd2cd 0%, #42c7ff 100%);
    }
  }
  .sure-order-page {
    height: 100vh;
    overflow-y: auto;
    position: relative;
    padding: 20rpx 20rpx 250rpx;
    box-sizing: border-box;
    .sure-order-content {
      position: relative;
      margin-top: 69rpx;
      border-radius: 20rpx;
      .mobile-input {
        background: #fff;
        border-radius: 18rpx;
        margin: 20rpx 0 31rpx 0;
      }
      .coupon-main {
        background: #fff;
        border-radius: 18rpx;
        padding-bottom: 1rpx;
        .usecoupon {
          margin: 0 20rpx;
          padding: 20rpx;
          background: #fffcf5;
          border-radius: 11px;
          .text {
            color: #fea43d;
            font-size: 24rpx;
          }
        }
      }
      .custom-zm-cell {
        // 其他zm-cell
        /deep/ .u-cell-group .u-cell-group__wrapper .u-cell__body {
          padding: 33rpx 20rpx 32rpx 20rpx !important;
        }
        // 套票中的zm-cell
        /deep/ .coupon-info-cell .u-cell-group .u-cell-group__wrapper .u-cell__body {
          padding: 0 !important;
        }
        /deep/.coupon-cell {
          margin-bottom: 0rpx !important;
        }
        /deep/.tehui-cell {
          margin-top: 25rpx !important;
        }
        /deep/.dianshang-cell {
          margin-top: 20rpx !important;
        }
        /* #ifdef H5 */
        &.coupon-cell {
          margin-bottom: 0rpx !important;
        }
        &.tehui-cell {
          margin-top: 25rpx !important;
        }
        &.dianshang-cell {
          margin-top: 20rpx !important;
        }
        /* #endif*/
        .title {
          font-size: 30rpx;
          font-weight: bold;
          margin-bottom: 18rpx;
          .more {
            height: 30rpx;
            line-height: 30rpx;
            font-size: 26rpx;
            font-weight: 400;
            color: #adb5b7;
          }
        }
        .label {
          font-size: 24rpx;
        }
        .value {
          .txt {
            margin-right: 18rpx;
          }
        }
      }
      .coupon-info {
        margin-top: 24rpx;
        border-radius: 18rpx;
      }
      .buy-notice {
        border-radius: 18rpx 18rpx 0 0;
      }
      .coupon-statement {
        /deep/ .refund-box {
          border-radius: 0 0 18rpx 18rpx;
        }
      }
      .card {
        display: flex;
        background: #fff4de;
        border-radius: 10rpx;
        margin: 16rpx;
        padding: 20rpx;
        .icon {
          width: 44rpx;
          height: 30rpx;
          margin-right: 20rpx;
          background-image: url(https://public-oss-file.zmaxfilm.com/applet/img/film-oxygen-uniapp/card-icon.png);
          background-repeat: no-repeat;
          background-size: 100% 100%;
        }
      }
    }
  }
</style>
